# -*- coding:utf-8 -*-
from datetime import datetime

from flask import render_template, current_app, g, abort, request

from ..news import news_blu
from ... import db
from ...models import News, Comment, CommentLike, User
from ...utils import utils
from ...utils.common import get_user_info, get_hits_info
from ...utils.resonse import info_jsonfy
from ...utils.response_code import RET


@news_blu.route("/<string:newsId>")
@get_user_info
@get_hits_info
def news_detail(newsId):
    """新闻详情页"""
    user = g.user
    newsBasicList = g.newsBasicList
    # 校验参数
    if not newsId:
        return info_jsonfy(RET.PARAMERR, "参数错误")
    # 查询新闻Id为newsId的数据
    news = None
    try:
        news = News.query.get(newsId)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        abort(404)
    news.clicks += 1

    # 收藏
    isCollected = False
    if user:
        if news in user.collection_news:
            isCollected = True

    # 评论信息
    try:
        comments = news.comments.order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")

    # 查询当前用户点赞了哪些评论
    commentLikeIdList = []
    if user:
        commentIdList = [comment.id for comment in comments]
        try:
            commentLikeIdListObj = CommentLike.query.filter(CommentLike.comment_id.in_(commentIdList),
                                                            CommentLike.user_id == user.id).all()
        except Exception as e:
            current_app.logger.error(e)
            return info_jsonfy(RET.DBERR, "数据库查询错误")
        commentLikeIdList = [commentLike.comment_id for commentLike in commentLikeIdListObj]

    commentList = []
    for comment in comments:
        commentDict = comment.to_dict()
        if comment.id in commentLikeIdList:
            commentDict["is_like"] = True
        commentList.append(commentDict)

    isFollowed = False
    if user and news.user:
        if news.user in user.followed:
            isFollowed = True

    data = {
        "newsInfo": news.to_dict(),
        "user": user.to_dict() if user else None,
        "newsBasicList": newsBasicList,
        "isCollected": isCollected,
        "isFollowed": isFollowed,
        "comments": commentList
    }
    return render_template("news/detail.html", data=data)


@news_blu.route("/news_collect", methods=["POST"])
@get_user_info
def news_collect():
    """收藏/取消收藏新闻"""
    user = g.user

    if not user:
        return info_jsonfy(RET.SESSIONERR, "用户未登录")

    # 校验参数
    data_dict = request.json
    newsId = data_dict.get("news_id")
    action = data_dict.get("action")

    if not newsId:
        return info_jsonfy(RET.PARAMERR, "新闻id不能为空")

    if action not in ["collect", "cancel_collect"]:
        return info_jsonfy(RET.PARAMERR, "参数错误")

    try:
        news = News.query.get(newsId)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "查询数据库失败")

    if not news:
        return info_jsonfy(RET.NODATA, "新闻数据不存在")

    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)
        else:
            return info_jsonfy(RET.DATAEXIST, "已收藏，请勿重复收藏")
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
        else:
            return info_jsonfy(RET.DATAEXIST, "未收藏，不允许取消收藏")

    return info_jsonfy(RET.OK, "success")


@news_blu.route("/news_comment", methods=["POST"])
@get_user_info
def news_comment():
    """评论新闻及回复别人评论"""
    user = g.user
    if not user:
        return info_jsonfy(RET.SESSIONERR, "用户未登录")

    # 校验参数
    data_dict = request.json
    newsId = data_dict.get("news_id")
    parentId = data_dict.get("parent_id")
    comment = data_dict.get("comment")

    if not all([newsId, comment]):
        return info_jsonfy(RET.PARAMERR, "参数错误")

    try:
        news = News.query.get(newsId)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "查询数据失败")

    if not news:
        return info_jsonfy(RET.NODATA, "该新闻不存在")

    commentObj = Comment()
    commentObj.news_id = newsId
    commentObj.content = comment
    commentObj.create_time = datetime.now()
    commentObj.user_id = user.id
    commentObj.id = utils.random_uuid()
    if parentId:
        commentObj.parent_id = parentId
    db.session.add(commentObj)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return info_jsonfy(RET.DBERR, "数据库保存失败")

    return info_jsonfy(RET.OK, "评论成功", commentObj.to_dict())


@news_blu.route("/comment_like", methods=["POST"])
@get_user_info
def comment_like():
    """评论点赞"""
    user = g.user
    if not user:
        return info_jsonfy(RET.SESSIONERR, "用户未登录")

    # 校验参数
    data_dict = request.json
    commentId = data_dict.get("comment_id")
    action = data_dict.get("action")

    if (not all([commentId, action])) or (action not in ["add", "remove"]):
        return info_jsonfy(RET.PARAMERR, "参数错误")

    try:
        commentObj = Comment.query.get(commentId)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")
    if not commentObj:
        return info_jsonfy(RET.NODATA, "评论不存在")

    try:
        commentLikeObj = CommentLike.query.filter(CommentLike.comment_id == commentId,
                                                  CommentLike.user_id == user.id).first()
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")
    if action == "add":
        if not commentLikeObj:
            commentLikeObj = CommentLike()
            commentLikeObj.comment_id = commentId
            commentLikeObj.user_id = user.id
            db.session.add(commentLikeObj)
            commentObj.like_count += 1
        else:
            return info_jsonfy(RET.DATAEXIST, "该用户已点过赞")
    else:
        if commentLikeObj:
            db.session.delete(commentLikeObj)
            commentObj.like_count -= 1
        else:
            return info_jsonfy(RET.DATAEXIST, "该用户未点过赞，无法取消")

    return info_jsonfy(RET.OK, "操作成功")


@news_blu.route("/followed_user", methods=["POST"])
@get_user_info
def followed_user():
    """关注作者"""
    user = g.user
    if not user:
        return info_jsonfy(RET.PARAMERR, "登录后再进行操作")

    dataDict = request.json
    action = dataDict.get("action")
    authorId = dataDict.get("user_id")
    if not action or not authorId:
        return info_jsonfy(RET.PARAMERR, "参数错误")
    if action not in ["follow", "unfollow"]:
        return info_jsonfy(RET.PARAMERR, "参数错误")

    try:
        author = User.query.get(authorId)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.NODATA, "数据库错误")
    if not author:
        return info_jsonfy(RET.NODATA, "未查询到当前作者信息")
    if action == "follow":
        if author not in user.followed:
            user.followed.append(author)
        else:
            return info_jsonfy(RET.DATAEXIST, "已关注，请勿重复关注")
    else:
        if author in user.followed:
            user.followed.remove(author)
        else:
            return info_jsonfy(RET.DATAEXIST, "未关注，不允许取消关注")

    return info_jsonfy(RET.OK, "success")
